//
// Created by korack on 25-5-11.
//

#include "GDialog.h"

#include "GBox.h"
#include "GColor.h"
#include "GLabel.h"
#include "Object.h"

struct _GDialog
{
        GWidget  parent_instance;
        GWidget *main_box;
        GWidget *title_label;
        GWidget *child_box;
};

static uint16_t
g_dialog_get_min_width(const GDialog *self)
{
        return g_widget_get_min_width(self->main_box);
}

static uint16_t
g_dialog_get_min_height(const GDialog *self)
{
        return g_widget_get_min_height(self->main_box);
}

static void
g_dialog_render(const GDialog *self,
                uint16_t       start_x,
                uint16_t       start_y,
                uint16_t       end_x,
                uint16_t       end_y)
{
        if (G_WIDGET(self)->is_update && !G_WIDGET(self)->force_render)
                return;

        const uint16_t width  = g_widget_get_min_width(self->main_box);
        const uint16_t height = g_widget_get_min_height(self->main_box);

        if (end_x - start_x > width)
                start_x += (end_x - start_x - width) / 2;
        end_x = start_x + width;
        if (end_y - start_y > height)
                start_y += (end_y - start_y - height) / 2;
        end_y = start_y + height;

        if (G_WIDGET(self)->force_render)
                g_widget_set_force_render(self->main_box);
        g_widget_render(self->main_box, start_x, start_y, end_x, end_y);

        G_WIDGET(self)->is_update = true;
}

GWidget *
g_dialog_new(void)
{
        GDialog *self = object_new(GDialog);
        g_widget_init(G_WIDGET(self),
                      G_WIDGET_NUMS_CALLBACK(g_dialog_get_min_width),
                      G_WIDGET_NUMS_CALLBACK(g_dialog_get_min_height),
                      G_WIDGET_RENDER(g_dialog_render));
        self->main_box    = g_box_new(G_ORIENTATION_VERTICAL, false);
        self->title_label = g_label_new();
        self->child_box   = NULL;

        g_box_append(G_BOX(self->main_box), self->title_label);
        g_box_set_background_color(G_BOX(self->main_box),
                                   G_COLOR(200, 200, 255));

        return G_WIDGET(self);
}

void
g_dialog_set_title(const GDialog *self, const unsigned char *title)
{
        g_label_set_text(G_LABEL(self->title_label), title);
        G_WIDGET(self)->is_update = false;
}

void
g_dialog_set_child(GDialog *self, GWidget *child)
{
        self->child_box = child;
        g_box_append(G_BOX(self->main_box), child);
        G_WIDGET(self)->is_update = true;
}
